package com.hsgene.supplier.service.impl;

import com.hsgene.common.DeleteFlagType;
import com.hsgene.common.util.basic.SimpleRegexUtils;
import com.hsgene.common.util.exception.ValidationException;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.supplier.condition.AgencyCondition;
import com.hsgene.supplier.domain.GeneticTestingAgency;
import com.hsgene.supplier.dto.GeneticTestingAgencyDto;
import com.hsgene.supplier.exception.SupplierErrorCode;
import com.hsgene.supplier.persistence.GeneticTestingAgencyMapper;
import com.hsgene.supplier.service.AgencyService;
import com.hsgene.supplier.service.api.ElasticsearchService;
import com.hsgene.supplier.service.api.GeneratorService;
import com.hsgene.supplier.service.api.GeneticAccountService;
import com.hsgene.user.domain.GeneticTestingOperationAccount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: //TODO
 * @ProjectName: hdas-geneshop
 * @Package: com.hsgene.supplier.service.impl
 * @Author: FX
 * @CreateDate: 2018/10/17 11:49
 * @Version: 1.0
 * Copyright: Copyright (c) 2018
 */
@Service
public class AgencyServiceImpl implements AgencyService {
    private final static Logger LOGGER = LoggerFactory.getLogger(AgencyServiceImpl.class);
    @Autowired
    GeneticTestingAgencyMapper geneticTestingAgencyMapper;
    @Autowired
    GeneratorService generatorService;
    @Autowired
    ElasticsearchService elasticsearchService;
    @Autowired
    GeneticAccountService geneticAccountService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult saveAgency(GeneticTestingAgency geneticTestingAgency) {
        GeneticTestingAgency geneticTestingAgency1 = geneticTestingAgencyMapper.selectByName(geneticTestingAgency.getName());
        if (geneticTestingAgency1 != null) {
            return ApiResult.fail(SupplierErrorCode.SUPPLIER_NAME_EXISTED);
        }
        boolean mobile = SimpleRegexUtils.isMobile(geneticTestingAgency.getPhone());
        if (!mobile) {
            return ApiResult.fail(SupplierErrorCode.PLEASE_ENTER_THE_CORRECT_PHONE_NUMBER);
        }
        ApiResult<GeneratorDto> generator = generatorService.getGenerator(null, null);
        if (!generator.isSucc()) {
            return ApiResult.fail(generator.getError());
        }
        geneticTestingAgency.setId(generator.getData().getSerialNumber());
        geneticTestingAgency.setCreateDateTime(new Date());
        geneticTestingAgency.setUpateDateTime(geneticTestingAgency.getCreateDateTime());
        geneticTestingAgency.setDeleteFlag(DeleteFlagType.NOT_DELETED.getCode());
        geneticTestingAgencyMapper.insertSelective(geneticTestingAgency);
        //添加机构账户
        ApiResult generatorAgency1 = addAccount(geneticTestingAgency);
        if (generatorAgency1 != null) return generatorAgency1;
        return ApiResult.succ();
    }

    private ApiResult addAccount(GeneticTestingAgency geneticTestingAgency) {
        GeneticTestingOperationAccount testingOperationAccount = new GeneticTestingOperationAccount();
        ApiResult<GeneratorDto> generatorAgency = generatorService.getGenerator(null, null);
        if (!generatorAgency.isSucc()) {
            return ApiResult.fail(generatorAgency.getError());
        }
        testingOperationAccount.setId(generatorAgency.getData().getSerialNumber());
        testingOperationAccount.setName(geneticTestingAgency.getAgencySendUsername());
        testingOperationAccount.setPhone(geneticTestingAgency.getPhone());
        testingOperationAccount.setRealName(geneticTestingAgency.getName());
        testingOperationAccount.setDeleteFlag(0);
        testingOperationAccount.setUserType(1);
        testingOperationAccount.setCompanyId(geneticTestingAgency.getId());

        ApiResult<NullObject> nullObjectApiResult = geneticAccountService.addAgencyAccount(testingOperationAccount);
        if (!nullObjectApiResult.isSucc()) {
            throw new IllegalStateException(nullObjectApiResult.getDesc());
        }
        return null;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult updateAgency(GeneticTestingAgency geneticTestingAgency) {
        GeneticTestingAgency geneticTestingAgency1 = geneticTestingAgencyMapper.selectByName(geneticTestingAgency.getName());
        if(geneticTestingAgency1!=null&&!geneticTestingAgency1.getId().equals(geneticTestingAgency.getId())){
            return ApiResult.fail(SupplierErrorCode.SUPPLIER_NAME_EXISTED);
        }
        boolean mobile = SimpleRegexUtils.isMobile(geneticTestingAgency.getPhone());
        if (!mobile) {
            return ApiResult.fail(SupplierErrorCode.PLEASE_ENTER_THE_CORRECT_PHONE_NUMBER);
        }
        geneticTestingAgency.setUpateDateTime(new Date());
        GeneticTestingAgency geneticTestingAgencyOld = geneticTestingAgencyMapper.selectByPrimaryKey(geneticTestingAgency.getId());
        geneticTestingAgencyMapper.updateByPrimaryKeySelective(geneticTestingAgency);
        //如果account没有就新增，有就更新
        GeneticTestingOperationAccount accountByCompanyId = geneticTestingAgencyMapper.getAccountByCompanyId(geneticTestingAgency.getId());
        if (accountByCompanyId != null) {
            //修改机构账户的名称
            GeneticTestingOperationAccount testingOperationAccount = new GeneticTestingOperationAccount();
            testingOperationAccount.setName(geneticTestingAgency.getAgencySendUsername());
            testingOperationAccount.setUpdateDateTime(new Date());
            testingOperationAccount.setCompanyId(geneticTestingAgency.getId());
            ApiResult<NullObject> nullObjectApiResult = geneticAccountService.updateAgencyAccount(testingOperationAccount);
            if (!nullObjectApiResult.isSucc()) {
                throw new ValidationException("修改账户异常");
            }
        } else {
            //添加机构账户
            ApiResult generatorAgency1 = addAccount(geneticTestingAgency);
            if (generatorAgency1 != null) {
                return generatorAgency1;
            }
        }
        //更改es套餐里面的所有机构名称
        String code = "for(HashMap m : ctx._source.orgs) {if(m.get('name') == '" + geneticTestingAgencyOld.getName() + "'){m.put('name','" + geneticTestingAgency.getName() + "')}}";
        ApiResult<NullObject> result = elasticsearchService.updateByQuery("orgs.name.keyword", geneticTestingAgencyOld.getName(), code);
        if (!result.isSucc()) {
            LOGGER.error("es更新结构名称失败");
            throw new ValidationException("es更新失败");
        }
        return ApiResult.succ();
    }

    @Override
    public ApiResult<Pagination<GeneticTestingAgencyDto>> getList(AgencyCondition condition) {
        int totalCount = geneticTestingAgencyMapper.getListCount(condition);
        Pagination<GeneticTestingAgencyDto> pagination = Pagination.newInstance(condition.getLimitHelper(), totalCount);
        if (totalCount > 0) {
            List<GeneticTestingAgency> list = geneticTestingAgencyMapper.getList(condition);
            List<GeneticTestingAgencyDto> collect = new ArrayList<>();
            int rowNumber = (condition.getLimitHelper().getPage() - 1) * condition.getLimitHelper().getSize();
            for (int i = 0, n = list.size(); i < n; i++) {
                GeneticTestingAgency geneticTestingAgency = list.get(i);
                GeneticTestingAgencyDto geneticTestingAgencyDto = new GeneticTestingAgencyDto();
                BeanUtils.copyProperties(geneticTestingAgency, geneticTestingAgencyDto);
                geneticTestingAgencyDto.setNumber(rowNumber + i + 1);
                GeneticTestingOperationAccount account = geneticTestingAgencyMapper.getAccountByCompanyId(geneticTestingAgency.getId());
                if (account != null) {
                    geneticTestingAgencyDto.setAgencySendUsername(account.getName());
                }
                collect.add(geneticTestingAgencyDto);
            }
            pagination.setResult(collect);
        } else {
            pagination.setResult(new ArrayList<>());
        }
        return ApiResult.succ(pagination);
    }

    @Override
    public ApiResult<GeneticTestingAgencyDto> getAgencyById(String id) {
        GeneticTestingAgency geneticTestingAgency = geneticTestingAgencyMapper.selectByPrimaryKey(id);
        GeneticTestingAgencyDto geneticTestingAgencyDto = new GeneticTestingAgencyDto();
        if (geneticTestingAgency != null) {
            BeanUtils.copyProperties(geneticTestingAgency, geneticTestingAgencyDto);
        }
        return ApiResult.succ(geneticTestingAgencyDto);
    }

    @Override
    public ApiResult deleteAgenecy(String id) {
        GeneticTestingAgency geneticTestingAgency = new GeneticTestingAgency();
        geneticTestingAgency.setId(id);
        geneticTestingAgency.setDeleteFlag(DeleteFlagType.DELETE.getCode());
        geneticTestingAgencyMapper.updateByPrimaryKeySelective(geneticTestingAgency);
        return ApiResult.succ();
    }

    @Override
    public ApiResult getAll() {
        List<GeneticTestingAgency> list = geneticTestingAgencyMapper.getAll();
        List<GeneticTestingAgencyDto> collect = new ArrayList<>();
        if (list != null && list.size() > 0) {
            collect = list.stream().map(c -> {
                GeneticTestingAgencyDto geneticTestingAgencyDto = new GeneticTestingAgencyDto();
                BeanUtils.copyProperties(c, geneticTestingAgencyDto);
                return geneticTestingAgencyDto;
            }).collect(Collectors.toList());
        }
        return ApiResult.succ(collect);
    }

    /***
     * 批量获取机构信息
     * @author jcl
     * @date 2018/11/13 14:05
     * @param ids 机构id
     * @return
     */
    @Override
    public ApiResult<List<GeneticTestingAgency>> getAgencyByIds(String ids) {
        String[] agencyIds = null;
        List<GeneticTestingAgency> agencyList = new ArrayList<>();
        if (!StringUtils.isEmpty(ids)) {
            agencyIds = ids.split(",");
            agencyList = geneticTestingAgencyMapper.getAgencyByIds(agencyIds);
        }
        return new ApiResult(200, "", "", agencyList);
    }

    @Override
    public ApiResult deleteAgencyMore(List<String> id) {
        if (id == null || id.size() == 0) {
            return ApiResult.fail(SupplierErrorCode.ID_IS_EMPTY);
        }
        geneticTestingAgencyMapper.deleteAgenecyMore(id);
        return ApiResult.succ();
    }

    @Override
    public ApiResult<NullObject> initAgencyPwd(String agencyId) {
        FieldChecker.checkEmpty(agencyId, "机构id");
        GeneticTestingAgency agency = geneticTestingAgencyMapper.selectByPrimaryKey(agencyId);
        if (agency == null || DeleteFlagType.DELETE.equals(DeleteFlagType.getEnum(agency.getDeleteFlag()))) {
            return ApiResult.fail(SupplierErrorCode.SUPPLIER_NOT_EXISTED);
        }
        // 查询机构用户信息
        GeneticTestingOperationAccount agencyAccount = geneticTestingAgencyMapper.getAccountByCompanyId(agency.getId());
        if (agencyAccount == null) {
            return ApiResult.fail(SupplierErrorCode.SUPPLIER_ACCOUNT_NOT_EXISTED);
        }
        // 初始化密码
        return geneticAccountService.resetAccountPassword(agencyAccount.getId());
    }
}
